package NG::Gen::Task::Task;
use strict;
use warnings;
use utf8;

use NG::Sys::App;

sub available {
	my $class = shift;
	my $proto_id = shift;
	my $proto = app()->reference("tasks_common")->get_by_key($proto_id);
	my $type = app()->reference("task_types")->get_by_key($proto->{type});
	my $package = "NG::Gen::Task::".$type->{class};
	Extend::_soft_require($package);
	my $self = bless {
				proto => $proto,
				type => $type,
			}, $package;
	return $self;
}
sub current {
	my $class = shift;
	my $user = shift;
	my $entry = shift;
	my $task = $user->task->get_by_entry($entry);
	my $proto = $task->proto;
	my $type = app()->reference("task_types")->get_by_key($proto->{type});
	my $package = "NG::Gen::Task::".$type->{class};
	Extend::_soft_require($package);
	my $self = bless {
				proto => $proto,
				type => $type,
				task => $task,
			}, $package;
	return $self;
}

sub assign {
	my $self = shift;
	my $user = shift;
	my $leader = shift;
	if(my $error = $self->before_assign($user,$leader)){
		return $error;
	}else{
		my $delay = $self->delay;
		my $entry = $user->task->insert({
					proto_id => $self->{proto}{entry},
					leader_id => $leader->entry,
					started => unixtime2timestamp(),
					done =>  unixtime2timestamp(time() + $delay),
				});
		$leader->current_task($entry);
		$self->{entry} = $entry;
		$self->after_assign($user,$leader);
		return 0;
	}
}
sub stop {
	my $self = shift;
	my $user = shift;
	my $leader = $user->leaders->get_by_entry($self->{task}->leader_id);

	if(my $error = $self->before_stop($user,$leader)){
		return $error;
	}else{
		$self->{task}->stoped(unixtime2timestamp());
		$leader->current_task(0);
		$self->after_stop($user,$leader);
		return 0;
	}
}



1;
